<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="保单号" prop="policyNumber">
              <el-input v-model="queryParams.policyNumber" placeholder="请输入保单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['Nyt7PolicyInsurance:Nyt7PolicyInsurance:add']" type="primary" plain icon="Plus" @click="handleAdd"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['Nyt7PolicyInsurance:Nyt7PolicyInsurance:edit']"
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate()"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['Nyt7PolicyInsurance:Nyt7PolicyInsurance:remove']"
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['Nyt7PolicyInsurance:Nyt7PolicyInsurance:export']" type="warning" plain icon="Download" @click="handleExport"
              >导出</el-button
            >
          </el-col>

          <el-col :span="1.5">
            <el-button type="warning" plain icon="Upload" @click="handleImport" v-hasPermi="['Nyt7BusinessEntity:Nyt7BusinessEntity:add']"
            >导入</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="Nyt7PolicyInsuranceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="60">
          <template #default="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="保单号" min-width="120px" max-width="140px" align="center" prop="policyNumber" />
        <el-table-column label="保险公司名称" min-width="280px" max-width="310px" align="center" prop="sysPost.postName" />
        <el-table-column label="地块编号" min-width="100px" max-width="120px" align="center" prop="plotDetailInfo.plotCode" />
        <el-table-column label="投保人" align="center" prop="farmerInsuranceInfo.farmerName" />
        <el-table-column label="投保标识" align="center" prop="insuranceIdentifier" />

        <el-table-column label="操作" min-width="120px" max-width="140px" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['Nyt7InsuranceProduct:Nyt7InsuranceProduct:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button
                v-hasPermi="['Nyt7PolicyInsurance:Nyt7PolicyInsurance:edit']"
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                v-hasPermi="['Nyt7PolicyInsurance:Nyt7PolicyInsurance:remove']"
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!--数据导入对话框 -->
    <el-dialog title="数据导入" v-model="excelOpen" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        :auto-upload="false"
        :on-change="handleChange"
        :limit="1"
        accept=".xlsx,.xls">
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <el-button class="ml-3" type="success" @click="submitUpload">上传</el-button>
        <template #tip>
          <div class="el-upload__tip">上传文件仅支持，xls/xlsx格式，文件大小不得超过20M</div>
        </template>
      </el-upload>
    </el-dialog>

    <!-- 添加或修改保单查询对话框 -->
    <el-dialog v-model="dialog1.visible" :title="dialog1.title" width="800px" append-to-body>
      <el-form ref="Nyt7PolicyInsuranceFormRef" :model="form" :rules="rules" label-width="110px">
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span class="title">保单基本信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
        <el-form-item label="保单号" prop="policyNumber">
          <el-input v-model="form.policyNumber" placeholder="请输入保单号" />
        </el-form-item>
            </el-col>
            <el-col :span="12">
        <el-form-item label="保险公司名称" prop="postId">
          <el-select v-model="form.postId" placeholder="请输入保险公司名称">
            <el-option v-for="post in postOptions" :key="post.postId" :label="post.postName" :value="post.postId" />
          </el-select>
        </el-form-item>
            </el-col>
            <el-col :span="12">

        <el-form-item label="地块编码" prop="plotDetailInfo.plotCode">
          <el-autocomplete
            v-model="form.plotDetailInfo.plotCode"
            :fetch-suggestions="debounce(queryEntitySearchPlot, 300)"
            placeholder="搜索地块编码...如：123"
            clearable
            :trigger-on-focus="true"
            @select="handleEntitySelectPlot"
          >
            <template #default="{ item }">
              <div class="suggestion-item">
                <div class="entity-name">{{ item.plotDetailInfo.plotCode }}</div>
                <div class="entity-info text-gray-400 text-sm">
                  <span>地块所有人: {{ item.plotDetailInfo.farmerInsuranceInfo.farmerName }}</span>
                  <span class="ml-2">区域: {{ item.plotDetailInfo.city }}</span>
                </div>
              </div>
            </template>
          </el-autocomplete>
        </el-form-item>
            </el-col>
            <el-col :span="12">
        <el-form-item label="投保人" prop="farmerInsuranceInfo.farmerName">
          <el-autocomplete
            v-model="form.farmerInsuranceInfo.farmerName"
            :fetch-suggestions="debounce(queryEntitySearchFarmer, 300)"
            placeholder="搜索投保人名称...如：张三"
            clearable
            :trigger-on-focus="true"
            @select="handleEntitySelectFarmer"
          >
            <template #default="{ item }">
              <div class="suggestion-item">
                <div class="entity-name">{{ item.farmerInsuranceInfo.farmerName }}</div>
                <div class="entity-info text-gray-400 text-sm">
                  <span>身份证号: {{ item.farmerInsuranceInfo.farmerIdCard }}</span>
                  <span class="ml-2">家庭成员: {{ item.farmerInsuranceInfo.familyMemberName }}</span>
                </div>
              </div>
            </template>
          </el-autocomplete>
        </el-form-item>
            </el-col>
            <el-col :span="12">
        <el-form-item label="投保标识" prop="insuranceIdentifier">
          <el-input v-model="form.insuranceIdentifier" placeholder="请输入投保标识" />
        </el-form-item>
            </el-col>
            <el-col :span="12">
        <el-form-item label="投保总户数" prop="totalInsuredHouseholds">
          <el-input v-model="form.totalInsuredHouseholds" placeholder="请输入投保总户数" />
        </el-form-item>
            </el-col>
            <el-col :span="12">
        <el-form-item label="作物代码" prop="cropCode">
          <el-input v-model="form.cropCode" placeholder="请输入作物代码" />
        </el-form-item></el-col>
            <el-col :span="12">
        <el-form-item label="险种代码" prop="insuranceTypeCode">
          <el-input v-model="form.insuranceTypeCode" placeholder="请输入险种代码" />
        </el-form-item></el-col>
            <el-col :span="12">
        <el-form-item label="总承包面积" prop="totalContractArea">
          <el-input v-model="form.totalContractArea" placeholder="请输入总承包面积" />
        </el-form-item>
            </el-col>
            <el-col :span="12">
        <el-form-item label="保费总额" prop="totalPremium">
          <el-input v-model="form.totalPremium" placeholder="请输入保费总额" />
        </el-form-item></el-col>
            <el-col :span="12">
        <el-form-item label="用户自缴总额" prop="totalSelfPaidByUser">
          <el-input v-model="form.totalSelfPaidByUser" placeholder="请输入用户自缴总额" />
        </el-form-item></el-col>
          </el-row>
          </el-card>
            <el-card class="mb-4">
              <template #header>
                <div class="card-header">
                  <span class="title">补贴数据</span>
                </div>
              </template>
              <el-row :gutter="20">
                <el-col :span="12">
        <el-form-item label="中央财政补贴总额" label-width="140px" prop="totalCentralFiscalSubsidy">
          <el-input v-model="form.totalCentralFiscalSubsidy" placeholder="请输入中央财政补贴总额" />
        </el-form-item>
                </el-col>
                <el-col :span="12">
        <el-form-item label="省级财政补贴总额" label-width="140px" prop="totalProvincialFiscalSubsidy">
          <el-input v-model="form.totalProvincialFiscalSubsidy" placeholder="请输入省级财政补贴总额" />
        </el-form-item></el-col>
                <el-col :span="12">
        <el-form-item label="地市财政补贴总额" label-width="140px" prop="totalMunicipalFiscalSubsidy">
          <el-input v-model="form.totalMunicipalFiscalSubsidy" placeholder="请输入地市财政补贴总额" />
        </el-form-item></el-col>
                <el-col :span="12">
        <el-form-item label="区县财政补贴总额" label-width="140px" prop="totalDistrictAndCountyFiscalSubsidy">
          <el-input v-model="form.totalDistrictAndCountyFiscalSubsidy" placeholder="请输入区县财政补贴总额" />
        </el-form-item></el-col>
                <el-col :span="12">
        <el-form-item label="其他财政补贴总额" label-width="140px" prop="totalOtherFiscalSubsidies">
          <el-input v-model="form.totalOtherFiscalSubsidies" placeholder="请输入其他财政补贴总额" />
        </el-form-item></el-col>
              </el-row>
        </el-card>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="dialog2.visible" :title="dialog2.title" width="800px" append-to-body>
      <el-form ref="Nyt7PolicyInsuranceFormRef" :model="form" :rules="rules" label-width="110px">
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span class="title">保单基本信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="保单号">
              {{ form.policyNumber }}
            </el-descriptions-item>
            <el-descriptions-item label="保险公司名称" prop="sysPost.companyName">
              {{ form.postId }}
            </el-descriptions-item>

            <el-descriptions-item label="地块编码" prop="plotDetailInfo.plotCode">
              {{ form.plotDetailInfo.plotCode }}

            </el-descriptions-item>

            <el-descriptions-item label="投保人" prop="farmerInsuranceInfo.farmerName">
              {{ form.farmerInsuranceInfo.farmerName }}

            </el-descriptions-item>
            <el-descriptions-item label="投保标识" prop="insuranceIdentifier">
              {{ form.insuranceIdentifier }}
            </el-descriptions-item>
            <el-descriptions-item label="投保总户数" prop="totalInsuredHouseholds">
              {{ form.totalInsuredHouseholds }}
            </el-descriptions-item>

            <el-descriptions-item label="作物代码" prop="cropCode">
              {{ form.cropCode }}
            </el-descriptions-item>
            <el-descriptions-item label="险种代码" prop="insuranceTypeCode">
              {{ form.insuranceTypeCode }}
            </el-descriptions-item>
            <el-descriptions-item label="总承包面积" prop="totalContractArea">
              {{ form.totalContractArea }}
            </el-descriptions-item>

            <el-descriptions-item label="保费总额" prop="totalPremium">
              {{ form.totalPremium }}
            </el-descriptions-item>
            <el-descriptions-item label="用户自缴总额" prop="totalSelfPaidByUser">
              {{ form.totalSelfPaidByUser }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span class="title">补贴数据</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="中央财政补贴总额" label-width="140px" prop="totalCentralFiscalSubsidy">
              {{ form.totalCentralFiscalSubsidy }}
            </el-descriptions-item>
            <el-descriptions-item label="省级财政补贴总额" label-width="140px" prop="totalProvincialFiscalSubsidy">
              {{ form.totalProvincialFiscalSubsidy }}
            </el-descriptions-item>
            <el-descriptions-item label="地市财政补贴总额" label-width="140px" prop="totalMunicipalFiscalSubsidy">
              {{ form.totalMunicipalFiscalSubsidy }}
            </el-descriptions-item>
            <el-descriptions-item label="区县财政补贴总额" label-width="140px" prop="totalDistrictAndCountyFiscalSubsidy">
              {{ form.totalDistrictAndCountyFiscalSubsidy }}
            </el-descriptions-item>
            <el-descriptions-item label="其他财政补贴总额" label-width="140px" prop="totalOtherFiscalSubsidies">
              {{ form.totalOtherFiscalSubsidies }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
          </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">返 回</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Nyt7PolicyInsurance" lang="ts">
import {
  listNyt7PolicyInsurance,
  getNyt7PolicyInsurance,
  delNyt7PolicyInsurance,
  addNyt7PolicyInsurance,
  updateNyt7PolicyInsurance,
  searchEntityFarmer, searchEntityPlot,
  exportSelected
} from '@/api/Nyt7PolicyInsurance/Nyt7PolicyInsurance';
import {
  Nyt7PolicyInsuranceVO,
  Nyt7PolicyInsuranceQuery,
  Nyt7PolicyInsuranceForm,
  EntitySearchResult

} from '@/api/Nyt7PolicyInsurance/Nyt7PolicyInsurance/types';
import { Nyt7FarmerInsuranceInfoVO } from '@/api/Nyt7FarmerInsuranceInfo/Nyt7FarmerInsuranceInfo/types';
import { listNyt7FarmerInsuranceInfo } from '@/api/Nyt7FarmerInsuranceInfo/Nyt7FarmerInsuranceInfo';
import { PostVO } from '@/api/system/post/types';
import { listPost } from '@/api/system/post';
import { listNyt7PlotDetailInfo } from '@/api/Nyt7PlotDetailInfo/Nyt7PlotDetailInfo';
import { Nyt7PlotDetailInfoVO } from '@/api/Nyt7PlotDetailInfo/Nyt7PlotDetailInfo/types';
import { Nyt7InsuranceProductVO } from '@/api/Nyt7InsuranceProduct/Nyt7InsuranceProduct/types';
import { getNyt7InsuranceProduct } from '@/api/Nyt7InsuranceProduct/Nyt7InsuranceProduct';
import { importExcel } from '@/api/Nyt7BusinessEntity/Nyt7BusinessEntity';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const Nyt7PolicyInsuranceList = ref<Nyt7PolicyInsuranceVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const Nyt7PolicyInsuranceFormRef = ref<ElFormInstance>();







const selectedRows = ref<Nyt7PolicyInsuranceVO[]>([]);






















const dialog1 = reactive<DialogOption>({
  visible: false,
  title: ''
});
const dialog2 = reactive<DialogOption>({
  visible: false,
  title: ''
});




const initFormData: Nyt7PolicyInsuranceForm = {
  farmerInsuranceInfo: {} as Nyt7FarmerInsuranceInfoVO,
  plotDetailInfo: {} as Nyt7PlotDetailInfoVO,
  sysPost: {} as PostVO,
  farmerId: undefined,
  plotId: undefined,
  postId: undefined,
  id: undefined,
  policyNumber: undefined,
  insuranceIdentifier: undefined,
  totalInsuredHouseholds: undefined,
  cropCode: undefined,
  insuranceTypeCode: undefined,
  totalContractArea: undefined,
  totalPremium: undefined,
  totalSelfPaidByUser: undefined,
  totalCentralFiscalSubsidy: undefined,
  totalProvincialFiscalSubsidy: undefined,
  totalMunicipalFiscalSubsidy: undefined,
  totalDistrictAndCountyFiscalSubsidy: undefined,
  totalOtherFiscalSubsidies: undefined
};
const data = reactive<PageData<Nyt7PolicyInsuranceForm, Nyt7PolicyInsuranceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    insuranceCompanyName: undefined,
    policyNumber: undefined,
    latitude: undefined,
    longitude: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
    policyNumber: [{ required: true, message: '保单号不能为空', trigger: 'blur' }],
    insuranceIdentifier: [{ required: true, message: '投保标识不能为空', trigger: 'blur' }],
    totalInsuredHouseholds: [{ required: true, message: '投保总户数不能为空', trigger: 'blur' }],
    cropCode: [{ required: true, message: '作物代码不能为空', trigger: 'blur' }],
    insuranceTypeCode: [{ required: true, message: '险种代码不能为空', trigger: 'blur' }],
    totalContractArea: [{ required: true, message: '总承包面积不能为空', trigger: 'blur' }],
    totalPremium: [{ required: true, message: '保费总额不能为空', trigger: 'blur' }],
    totalSelfPaidByUser: [{ required: true, message: '用户自缴总额不能为空', trigger: 'blur' }],
    totalCentralFiscalSubsidy: [{ required: true, message: '中央财政补贴总额不能为空', trigger: 'blur' }],
    totalProvincialFiscalSubsidy: [{ required: true, message: '省级财政补贴总额不能为空', trigger: 'blur' }],
    totalMunicipalFiscalSubsidy: [{ required: true, message: '地市财政补贴总额不能为空', trigger: 'blur' }],
    totalDistrictAndCountyFiscalSubsidy: [{ required: true, message: '区县财政补贴总额不能为空', trigger: 'blur' }],
    totalOtherFiscalSubsidies: [{ required: true, message: '其他财政补贴总额不能为空', trigger: 'blur' }],
    postId: [{ required: true, message: '保险公司不能为空', trigger: 'blur' }],
    'plotDetailInfo.plotCode': [{ required: true, message: '地块编号不能为空', trigger: 'blur' }],
    'farmerInsuranceInfo.farmerName': [{ required: true, message: '农户名不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
const entity = ref<EntitySearchResult>();

/** 查询保单查询列表 */
const getList = async () => {
  loading.value = true;
  const res = await listNyt7PolicyInsurance(queryParams.value);
  Nyt7PolicyInsuranceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog1.visible = false;
  dialog2.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  Nyt7PolicyInsuranceFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// /** 多选框选中数据 */
// const handleSelectionChange = (selection: Nyt7PolicyInsuranceVO[]) => {
//   ids.value = selection.map((item) => item.id);
//   single.value = selection.length != 1;
//   multiple.value = !selection.length;
// };



   const handleSelectionChange = (selection: Nyt7PolicyInsuranceVO[]) => {
     ids.value = selection.map(item => item.id);
     selectedRows.value = selection; // 存储选中的数据行
     single.value = selection.length !== 1;
     multiple.value = selection.length === 0;
   }



















/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog1.visible = true;
  dialog1.title = '添加保单查询';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: Nyt7PolicyInsuranceVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getNyt7PolicyInsurance(_id);
  Object.assign(form.value, res.data);
  console.log('form', form.value.farmerInsuranceInfo.farmerName);
  //console.log(form.value.nyt7PlotDetailInfoVo.plotCode);
  //console.log(form.value.nyt7FarmerInsuranceInfoVo.farmerName);
  dialog1.visible = true;
  dialog1.title = '修改保单查询';
};

/** 详情按钮操作 */
const handleView = async (row?: Nyt7InsuranceProductVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getNyt7PolicyInsurance(_id);
  Object.assign(form.value, res.data);
  dialog2.visible = true;
  dialog2.title = '保单详情';
}

/** 提交按钮 */
const submitForm = () => {
  Nyt7PolicyInsuranceFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateNyt7PolicyInsurance(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addNyt7PolicyInsurance(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog1.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: Nyt7PolicyInsuranceVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除保单查询编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delNyt7PolicyInsurance(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
  dialog1.visible = false;
};



// /** 导出按钮操作 */
// const handleExport = () => {
//   proxy?.download(
//     'Nyt7PolicyInsurance/Nyt7PolicyInsurance/export',
//     {
//       ...queryParams.value
//     },
//     `Nyt7PolicyInsurance_${new Date().getTime()}.xlsx`
//   );
// };







  //  const handleExport = () => {
  //    if (selectedRows.value.length > 0) {
  //      // 导出选中的数据
  //      exportSelectedRows(selectedRows.value);
  //    } else {
  //      // 导出所有数据
  //      proxy?.download(
  //        'Nyt7PolicyInsurance/Nyt7PolicyInsurance/export',
  //        {
  //          ...queryParams.value
  //        },
  //        `Nyt7PolicyInsurance_${new Date().getTime()}.xlsx`
  //      );
  //    }
  //  }

  //  const exportSelectedRows = async (rows: Nyt7PolicyInsuranceVO[]) => {
  //    try {
  //      const response = await exportSelected(rows.map(row => row.id));
  //      const url = window.URL.createObjectURL(new Blob([response]));
  //      const link = document.createElement('a');
  //      link.href = url;
  //      link.setAttribute('download', `Nyt7PolicyInsurance_${new Date().getTime()}.xlsx`);
  //      document.body.appendChild(link);
  //      link.click();
  //    } catch (error) {
  //      console.error('导出选中的数据失败:', error);
  //      proxy?.$modal.msgError('导出选中的数据失败');
  //    }
  //  }


const handleExport = () => {
  if (selectedRows.value.length > 0) {
    // 输出选中的行数据，便于调试
    console.log('选中的行数据:', selectedRows.value);
    // 导出选中的数据
    exportSelectedRows(selectedRows.value);
  } else {
    // 输出查询参数，便于调试
    console.log('查询参数:', queryParams.value);
    // 导出所有数据
    proxy?.download(
      'Nyt7PolicyInsurance/Nyt7PolicyInsurance/export',
      {
        ...queryParams.value
      },
      `Nyt7PolicyInsurance_${new Date().getTime()}.xlsx`
    );
  }
}

const exportSelectedRows = async (rows: Nyt7PolicyInsuranceVO[]) => {
  try {
    // 输出要导出的数据列表，便于调试
    console.log('开始导出选中的数据:', rows);

    // 提取选中的数据的ID列表
    const ids = rows.map(row => row.id);
    // 输出提取的ID列表，便于调试
    console.log('选中的数据ID列表:', ids);

    // 调用API导出选中的数据
    const response = await exportSelected(ids);
    // 输出API响应，便于调试
    console.log('导出响应:', response);

    // 创建一个Blob对象，用于创建下载链接
    const url = window.URL.createObjectURL(new Blob([response]));
    // 输出创建的URL，便于调试
    console.log('创建的URL:', url);

    // 创建一个<a>元素，用于触发文件下载
    const link = document.createElement('a');
    // 设置下载链接的href属性
    link.href = url;
    // 设置下载文件的名称
    link.setAttribute('download', `Nyt7PolicyInsurance_${new Date().getTime()}.xlsx`);
    // 输出创建的下载链接，便于调试
    console.log('创建的下载链接:', link);

    // 将<a>元素添加到文档中
    document.body.appendChild(link);
    // 触发点击事件，开始下载文件
    link.click();
    // 输出下载链接点击完成的信息，便于调试
    console.log('下载链接点击完成');

    // 移除<a>元素，清理DOM
    document.body.removeChild(link);
  } catch (error) {
    // 捕获并输出错误信息，便于调试
    console.error('导出选中的数据失败:', error);
    // 显示错误提示给用户
    proxy?.$modal.msgError('导出选中的数据失败');
  }
}




















const farmerManagementList = ref<Nyt7FarmerInsuranceInfoVO[]>([]);
const farmerOptions = ref<Nyt7FarmerInsuranceInfoVO[]>([]);

//获取农户数据
const getFarmerManagementList = async () => {
  const res = await listNyt7FarmerInsuranceInfo();
  farmerManagementList.value = res.rows;
  farmerOptions.value = farmerManagementList.value;
};

const plotManagementList = ref<Nyt7PlotDetailInfoVO[]>([]);
const plotOptions = ref<Nyt7PlotDetailInfoVO[]>([]);

//获取地块
const getPlotManagementList = async () => {
  const res = await listNyt7PlotDetailInfo();
  plotManagementList.value = res.rows;
  plotOptions.value = plotManagementList.value;
};

const postList = ref<PostVO[]>([]);
const postOptions = ref<PostVO[]>([]);

//获取保险公司数据
const getPostList = async () => {
  const res = await listPost();
  postList.value = res.rows;
  postOptions.value = postList.value;
};

// 防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: NodeJS.Timeout | null = null;
  return (...args: any[]) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(null, args);
    }, delay);
  };
};

// 实体搜索建议
const queryEntitySearchFarmer = async (queryString: string, cb: (data: EntitySearchResult[]) => void) => {
  if (queryString.length < 1) {
    cb([]);
    return;
  }

  try {
    const res = await searchEntityFarmer(queryString);

    const suggestions = res.data || [];
    cb(suggestions);
  } catch (error) {
    console.error('获取搜索建议失败:', error);
    proxy?.$modal.msgError('获取搜索建议失败');
    cb([]);
  }
};
const queryEntitySearchPlot = async (queryString: string, cb: (data: EntitySearchResult[]) => void) => {
  if (queryString.length < 1) {
    cb([]);
    return;
  }

  try {
    const res = await searchEntityPlot(queryString);
    const suggestions = res.data || [];
    console.log(suggestions[0].plotDetailInfo.farmerInsuranceInfo.farmerName);
    cb(suggestions);
  } catch (error) {
    console.error('获取搜索建议失败:', error);
    proxy?.$modal.msgError('获取搜索建议失败');
    cb([]);
  }
};

// 处理实体选择
const handleEntitySelectFarmer = (item: EntitySearchResult) => {
  form.value.farmerId = item.farmerInsuranceInfo.id;
  form.value.farmerInsuranceInfo.farmerName = item.farmerInsuranceInfo.farmerName;
};
const handleEntitySelectPlot = (item: EntitySearchResult) => {
  form.value.plotId = item.plotDetailInfo.id;
  form.value.plotDetailInfo.plotCode = item.plotDetailInfo.plotCode;
};


/* 打开数据导入的对话框 */
const excelOpen = ref(false);

function handleImport() {
  excelOpen.value = true;
}

// 存储选择的文件
const selectedFile = ref(null);

// 文件选择变化时的处理
const handleChange = (file) => {
  selectedFile.value = file.raw;
};

// 提交上传
const submitUpload = async () => {
  if (!selectedFile.value) {
    proxy?.$modal.msgError('请先选择文件');
    return;
  }

  try {
    proxy?.$modal.loading('正在上传excel，请稍候...');
    const res = await importExcel(selectedFile.value);
    if (res.code === 200) {
      proxy?.$modal.msgSuccess('上传excel成功');
      excelOpen.value = false;
      getList();
    } else {
      proxy?.$modal.msgError(res.msg);
    }
  } catch (error) {
    proxy?.$modal.msgError('上传excel失败');
  } finally {
    proxy.$modal.closeLoading();
    uploadRef.value.clearFiles();
  }
};

onMounted(() => {
  getList();
  getPostList();
  getFarmerManagementList();
  getPlotManagementList();
});
</script>

<style scoped>
.suggestion-item {
  padding: 4px 0;
}

.entity-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.entity-info {
  font-size: 12px;
  color: #999;
}

.entity-info span {
  margin-right: 8px;
}
</style>
